<template>
  <div class="addUser">
    <div>
      <div
        :class="{'leftForm2':disabled||platformManager}"
        class="leftForm"
      >
        <div>
          <el-form
            ref="form"
            :rules="rules"
            :model="form"
            label-width="90px"
          >
            <el-form-item label="用户账号" prop="account">
              <el-input v-if="!disabled" v-model="form.account" placeholder="请输入用户账号" />
              <div v-else class="accountCss" @click="handleMoveUser"> {{ form.account }} </div>
            </el-form-item>
            <el-form-item label="所属部门" prop="deptName">
              <el-input v-model="form.deptName" :disabled="disabled" placeholder="请填写所属部门" />
            </el-form-item>
            <el-form-item v-if="form.loginType != 1" label="CA证书号" prop="caCard">
              <el-input v-model="form.caCard" :disabled="disabled" placeholder="请填写CA证书号" />
            </el-form-item>
            <el-form-item label="身份证号">
              <el-input v-model="form.cardNumber" :disabled="disabled" clearable placeholder="请填写身份证号" />
            </el-form-item>
            <el-form-item label="出生日期" prop="birthday">
              <el-date-picker
                v-model="form.birthday"
                :disabled="disabled"
                class="date-picker"
                type="date"
                style="width: 100%"
                value-format="yyyy-MM-dd"
                placeholder="出生年月"
              />
            </el-form-item>
            <el-form-item label="电子邮箱" prop="email">
              <el-input v-model="form.email" :disabled="disabled" placeholder="请输入电子邮箱" />
            </el-form-item>
            <el-form-item label="用户类型" prop="userType">
              <el-select
                v-model="form.userType"
                :disabled="disabled"
                style="width: 100%"
                placeholder="请选择用户类型"
                @change="userChange"
              >
                <el-option
                  v-for="item of showUserTypeList"
                  :key="item.encode"
                  :value="item.encode"
                  :label="item.name"
                />
              </el-select>

            </el-form-item>
            <el-form-item label="状态">
              <el-radio-group
                v-model="form.status"
                :disabled="disabled"
              >
                <el-radio :label="1">启用</el-radio>
                <el-radio :label="0">停用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-form>
        </div>
        <div>
          <el-form
            ref="form2"
            :rules="rules"
            :model="form"
            label-width="80px"
          >
            <el-form-item
              label="用户名称"
              prop="userName"
            >
              <el-input
                v-model="form.userName"
                :disabled="disabled"
                placeholder="请输入用户名称"
              />
            </el-form-item>
            <el-form-item label="登录方式" prop="loginType">
              <el-select
                v-model="form.loginType"
                :disabled="disabled"
                style="width: 100%"
                placeholder="请选择登录方式"
              >
                <el-option
                  v-for="item of loginType"
                  :key="item.encode"
                  :value="item.encode"
                  :label="item.name"
                />
              </el-select>

            </el-form-item>
            <el-form-item
              label="用户密码"
              prop="password"
            >
              <el-input
                v-model="form.password"
                :disabled="disabled"
                type="password"
                placeholder="请填写用户密码"
              />
            </el-form-item>
            <el-form-item
              label="密码确认"
              prop="passwordConfirm"
            >
              <el-input
                v-model="form.passwordConfirm"
                :disabled="disabled"
                placeholder="请确认密码"
                type="password"
              />
            </el-form-item>
            <el-form-item label="性别">
              <el-select
                v-model="form.gender"
                :disabled="disabled"
                style="width: 100%"
                placeholder="请选择性别"
              >
                <el-option
                  v-for="item of [{encode:1,name:'男'},{encode:0,name:'女'}]"
                  :key="item.encode"
                  :value="item.encode"
                  :label="item.name"
                />
              </el-select>

            </el-form-item>
            <el-form-item label="手机号码" prop="phone">
              <el-input
                v-model="form.phone"
                :disabled="disabled"
                placeholder="请填写手机号码"
              />
            </el-form-item>
            <el-form-item label="有效期限" prop="validDate">
              <el-date-picker
                v-model="form.validDate"
                :disabled="disabled"
                style="width: 100%"
                type="date"
                class="date-picker"
                value-format="yyyy-MM-dd"
                placeholder="请选择有效期限"
              />
            </el-form-item>

          </el-form>
        </div>

      </div>
      <div
        v-if="!disabled && !platformManager"
        class="rightList"
      >
        <el-row>
          <el-col
            :span="6"
            class="searchT"
          >
            <span>定位组织:</span>
          </el-col>
          <el-col :span="16">
            <el-input
              v-model="searchVal"
              placeholder="输入组织编码/名称定位组织"
            />
          </el-col>

        </el-row>
        <div class="orglist">
          <div>
            <el-tree
              ref="tree"
              :key="treeKey"
              :data="orgList"
              :filter-node-method="filterNode"
              :default-checked-keys="defaultCheckedOrg"
              :props="defaultProps"
              show-checkbox
              node-key="phid"
              highlight-current
            />
          </div>

        </div>
      </div>
    </div>

    <p>
      <button
        class="greenBtn"
        @click="$emit('close')"
      >取消</button>
      <button
        class="greenBtn"
        @click="keepOrg"
      >保存</button>
    </p>
    <!-- 默认组织 -->
    <el-dialog
      v-if="defaultOrgShow"
      :close-on-click-modal="false"
      :visible.sync="defaultOrgShow"
      width="400px"
      append-to-body
      title="选择默认组织"
      custom-class="blueDialog"
    >
      <div>
        <el-input
          v-model="defaultOrg"
          prefix-icon="el-icon-search"
          placeholder="请输入组织名称搜索"
        />
      </div>
      <div
        style="max-height: 400px;
        overflow: auto;margin:10px 0;"
      >
        <ul>
          <li
            v-for="item of showOrgList"
            :key="item.phid"
          >
            <el-radio
              v-model="defaultChecked"
              :label="item.phid"
            >{{ item.name }}</el-radio>
          </li>
        </ul>
      </div>
      <p style="text-align:right">
        <button
          class="greenBtn"
          @click="defaultOrgShow=false"
        >返回</button>
        <button
          :class="{grayBtn:!defaultChecked}"
          class="greenBtn"
          @click="finish"
        >确定</button>
      </p>
    </el-dialog>
  </div>
</template>
<script>
import accountTransfer from './acountTransfer'
import { getUserInfoById, transferAccount } from '@/api/user/index'
import { getOrgTreeList, getOrgGroupTreeList, getOrgListByUserId, getOrgGroupListByUserId } from '@/api/organization'
export default {
  name: 'AddUser',
  props: {
    type: {
      type: String,
      default: 'add'
    },
    info: {
      type: Array,
      default() {
        return []
      }
    },
    tableData: {
      type: Array,
      default() {
        return []
      }
    }
  },
  data() {
    var validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== this.form.password) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    return {
      platformManager: false, // 平台管理员隐藏组织
      filterData: [], // 筛选的用户数据
      selectUser: '', // 选中的用户
      userSearch: '', // 搜索用户
      userSelectShow: false, // 账号移交选择用户
      disabled: false, // 不可编辑
      form: {
        accout: '',
        deptName: '',
        caCard: '',
        passwordConfirm: '',
        password: '',
        birthday: '',
        email: '',
        status: 1,
        userType: null,
        userName: '',
        loginType: 1,
        cardNumber: '',
        gender: null,
        phone: '',
        validDate: ''
      },
      rules: {
        account: [
          { required: true, message: '用户账号不能为空', trigger: 'blur' }
        ],
        caCard: [
          { required: true, message: '请填写CA证书号', trigger: 'blur' }
        ],
        userName: [
          { required: true, message: '请填写用户名称', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '密码不能为空', trigger: 'blur' }
        ],
        passwordConfirm: [
          { validator: validatePass2, required: true, trigger: 'blur' }
        ],
        userType: [
          { required: true, type: 'number', message: '请选择用户类型', trigger: 'change' }
        ],
        loginType: [
          { required: true, type: 'number', message: '请选择登录方式', trigger: 'change' }
        ],
        validDate: [
          { required: true, validator: (rule, value, cb) => !value ? cb('请选择有效期限') : cb() }
        ],
        gender: [
          { required: true, type: 'number', message: '请选择性别', trigger: 'change' }
        ],
        phone: [
          { required: true, message: '请输入号码', trigger: 'blur' }
        ]
      },
      searchVal: '', // 搜索值
      defaultOrg: '', // 默认组织
      defaultOrgList: [], // 选中的组织
      defaultOrgShow: false, // 显示选择默认组织
      defaultSelect: {}, // 选中的默认组织
      defaultChecked: false,
      orgList: [],
      flatOrgList: {}, // 扁平化orgList 并存储节点信息
      orgIds: [], // 用户的组织 或者 组织单元
      treeKey: 0,
      defaultCheckedOrg: [], // 默认选择的节点
      loginType: [
        { encode: 1, name: '账号密码登录' },
        { encode: 2, name: 'CA登录' },
        { encode: 3, name: '账号密码+CA证书' }
      ],
      userTypeList: [
        { encode: 1, name: '操作员' },
        { encode: 3, name: '平台管理员' },
        { encode: 4, name: '组织单元管理员' },
        { encode: 5, name: '组织管理员' }
      ],
      defaultProps: {
        children: 'children',
        label: 'name'
      }
    }
  },
  computed: {
    showOrgList() {
      return this.defaultOrgList.filter(v => v.name.includes(this.defaultOrg))
    },
    orgId() {
      return this.$store.state.user.orgId
    },
    showUserTypeList() {
      const userType = this.$store.state.user.userType
      if (userType === 5) {
        return this.userTypeList.filter(v => [1, 5].includes(v.encode))
      } else if (userType === 4) {
        return this.userTypeList.filter(v => [1, 4, 5].includes(v.encode))
      } else {
        return this.userTypeList
      }
    }
  },
  watch: {
    searchVal(val) {
      this.$refs.tree.filter(val)
    },

    userSearch(val) {
      const tData = this.tableData.filter(item => {
        return !item.checked
      })
      if (val) {
        this.filterData = JSON.parse(JSON.stringify(tData)).filter(data => {
          return data.account.indexOf(val) !== -1 || data.userName.indexOf(val) !== -1
        })
      } else {
        this.filterData = JSON.parse(JSON.stringify(tData))
      }
    },
    'form.userType': {
      // 手动修改 type 不会触发 change event
      handler() {
        this.platformManager = this.form.userType === 3
      }
    }
  },
  async mounted() {
    if (this.info.length) {
      const { data: { loginInfo, userInfo, orgIds }} = await getUserInfoById({ phid: this.info[0].phid })
      this.form = {
        ...(loginInfo || {}),
        ...userInfo,
        loginType: +loginInfo.loginType,
        status: userInfo.status,
        passwordConfirm: loginInfo.password
      }
      this.orgIds = orgIds
    }
    if (this.type === 'move') {
      this.disabled = true
      this.filterData = this.tableData.filter(item => !item.checked)
      this.filterData = JSON.parse(JSON.stringify(this.filterData))
    }
    this.getOrgList()
  },
  methods: {
    // 过滤
    filterNode(value, data) {
      if (!value) return true
      return data.name.includes(value) || data.encode.includes(value)
    },
    // 新增类型改变
    userChange() {
      if (this.form.userType === 3) {
        this.platformManager = true
      } else {
        this.platformManager = false
        this.getOrgList()
      }
    },
    // 获取组织
    // { encode: 1, name: '操作员' }
    // { encode: 3, name: '平台管理员' }
    // { encode: 4, name: '组织单元管理员' }
    // { encode: 5, name: '组织管理员' }
    async getOrgList() {
      const { userType } = this.form
      const loginUserType = this.$store.state.user.userType
      console.log(userType)
      console.log(loginUserType)
      // 没有选择类型或者选择平台管理员直接返回
      if (!userType || userType === 3) return
      switch (userType) {
        // 组织管理员拉取组织tree
        case 1:
        case 5:
          if (loginUserType === 3 || loginUserType === 2) {
            this.handleGetOrgTreeList()
          } else if (loginUserType === 5 || loginUserType === 4) {
            // 组织管理员只能获取组织列表
            this.handleGetOrgList()
          }
          break
        // 组织单元管理员拉取组织单元树
        case 4:
          if (loginUserType === 3 || loginUserType === 2) {
            this.handleGetOrgGroupTreeList()
          } else {
            this.handleGetOrgGroupList()
          }
          break
        default:
          break
      }
    },
    handleGetOrgList() {
      getOrgListByUserId(this.$store.state.user.userid).then(({ data }) => {
        this.orgList = data || []
        this.handleCheckFlatOrgList()
      }).catch((err) => {
        console.log('eerr', err)
      })
    },
    handleGetOrgTreeList() {
      getOrgTreeList().then(({ data }) => {
        this.orgList = data || []
        this.handleCheckFlatOrgList()
      }).catch((err) => {
        console.log('eerr', err)
      })
    },
    handleGetOrgGroupTreeList() {
      getOrgGroupTreeList().then(({ data }) => {
        this.orgList = data || []
        this.handleCheckFlatOrgList()
      }).catch((err) => {
        console.log('eerr', err)
      })
    },
    handleGetOrgGroupList() {
      getOrgGroupListByUserId(this.$store.state.user.userid).then(({ data }) => {
        this.orgList = data || []
        this.handleCheckFlatOrgList()
      }).catch((err) => {
        console.log('eerr', err)
      })
    },
    handleCheckFlatOrgList() {
      if (this.type === 'update') {
        this.handleFlatOrgList()
        this.handleDefaultCheckedOrg()
      }
    },
    handleFlatOrgList() {
    // 递归遍历数组
      const mapTreeArr = list => list.forEach(org => {
        const {
          children,
          phid,
          ...rest
        } = org
        this.flatOrgList[phid] = rest
        if (children && children.length) {
          this.flatOrgList[phid].hasChildren = true
          mapTreeArr(children)
        }
      })
      this.treeKey++
      mapTreeArr(this.orgList)
    },
    handleDefaultCheckedOrg() {
      this.defaultCheckedOrg = this.orgIds.filter(
        id => this.flatOrgList[id] && !this.flatOrgList[id].hasChildren
      )
    },
    keepOrg() {
      if (this.type === 'move') { // 账号移交
        transferAccount({
          newUserId: this.selectUser.phid,
          oldUserId: this.info[0].phid
        }).then(res => {
          this.$msgBox.show('账号移交成功')
          this.$emit('close')
        }).catch(err => {
          this.$msgBox.error(err.message || '账号移交失败')
        })
      } else {
        Promise.all([this.$refs.form.validate(), this.$refs.form2.validate()])
          .then(([valid1, valid2]) => {
            if (this.form.userType === 3) { // 平台管理员直接保存,不选默认\组织
              this.finish()
              return
            }
            if (this.form.userType === 4) { // 组织单元管理员直接保存,不选默认\组织
              this.defaultOrgList = this.$refs.tree.getCheckedNodes()
              this.defaultChecked = false
              this.finish()
              return
            }
            this.defaultOrgList = this.$refs.tree.getCheckedNodes()
            this.defaultChecked = this.type === 'update' ? this.form.orgId : false
            this.defaultOrgShow = true
          }).catch(() => {})
      }
    },
    handleSubmit() {

    },
    // 完成
    finish() {
      let form = null
      form = JSON.parse(JSON.stringify(this.form))
      console.log(form)
      if (!this.defaultChecked && this.form.userType !== 3 && this.form.userType !== 4) {
        return
      }
      if (this.form.userType === 3) { // 平台管理员
        // form.enabledmark = form.enabledmark === '启用' ? 1 : 0
        this.$emit('close', form)
        return
      }
      if (this.form.userType === 4) { // 组织单元管理员
        // form.enabledmark = form.enabledmark === '启用' ? 1 : 0
        form.orgIds = this.defaultOrgList.map(org => org.phid)
        if (!form.orgIds.length) {
          this.$msgBox.error('请选择组织单元')
        } else {
          this.$emit('close', form)
        }
        return
      }

      if (this.type === 'add' || this.type === 'update') {
        form.orgId = this.defaultChecked
        this.form.orgId = this.defaultChecked
        // form.enabledmark = form.enabledmark === '启用' ? 1 : 0
        form.orgIds = this.defaultOrgList.map(org => org.phid)
      }

      this.$emit('close', form)
    },
    showUserSelect() {
      this.userSelectShow = true
    },
    handleMoveUser() {
      const moveData = this.tableData.filter(v => v.checked)
      if (moveData.length !== 1) {
        this.$msgBox.error('请选择一个数据操作')
        return
      }
      const { userType, phid } = moveData[0]
      this.$popup(accountTransfer, { userType, phid }).then(selectUser => {
        this.selectUser = selectUser
        this.form.account = selectUser.account
      }).catch(err => {
        console.log('err', err)
      })
    }
  }
}
</script>
<style lang="scss" scoped>
@import "@/styles/variables.scss";
.addUser {
  > div {
    width: 100%;
    height: 500px;

    > div {
      float: left;
      height: 100%;
    }
  }
  > p {
    text-align: right;
  }
}
.leftForm {
  width: 65%;
  padding-right: 30px;
  position: relative;
  &:after {
    position: absolute;
    content: "";
    right: 0;
    top: 10px;
    bottom: 10px;
    width: 1px;
    background: $borderGray;
  }
  > div {
    width: 48%;
    height: 100%;
    float: left;
    text-align: center;
    &:nth-of-type(2) {
      margin-left: 4%;
    }
  }
  >>> .el-select {
    width: 100%;
  }
  >>> .el-date-editor.el-input {
    width: 100%;
  }
}
.leftForm2 {
  width: 100%;
  &::after {
    display: none;
  }
}
.rightList {
  width: 35%;
}
.searchT {
  height: 36px;
  line-height: 36px;
  text-align: right;
  padding-right: 5px;
}
.orglist {
  padding: 0 0 50px 20px;
  height: 100%;
  margin-top: 10px;
  > div {
    width: 100%;
    height: 100%;
    overflow: auto;
  }
}
.accountCss {
  border: 1px solid #dfe4ed;
  border-radius: 4px;
  cursor: pointer;
  text-align: left;
  padding: 0 15px;
}
.tableCon {
  margin: 10px 0 0px;
}
.btnCon {
  text-align: right;
  margin-top: 5px;
  margin-right: 20px;
}
</style>
<style lang="scss">
@import "@/styles/variables.scss";
.blueDialog {
  border-radius: 10px;
  overflow: hidden;
  .el-dialog__header {
    background: $btn_blue;
    .el-dialog__title {
      color: #fff;
    }
  }
}
</style>
